package cc.customer.web.bigEpResoure;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;

import javax.servlet.http.HttpServletResponse;

import cc.customer.system.dao.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

import cc.customer.bigEmport.damain.BigEmp;
import cc.customer.bigEmport.damain.EpRecords;
import cc.customer.bigEmport.damain.EprRecords;
import cc.customer.bigEmport.damain.IpRecords;
import cc.customer.bigEmport.services.BigEmpIrecords;
import cc.customer.bigEmport.services.BigEmpServices;
import cc.customer.common.domain.QueryRequest;
import cc.customer.common.domain.ResponseBo;
import cc.customer.common.utils.Constant;
import cc.customer.common.utils.DateUtil;
import cc.customer.common.utils.FebsUtil;
import cc.customer.common.utils.FileUploadUtil;
import cc.customer.common.utils.FileUtils;
import cc.customer.common.utils.Utils;
import cc.customer.expCustomer.services.ExEmpServices;
import cc.customer.system.domain.MyUser;
import cc.customer.system.service.UserService;
import cc.customer.web.sys.controller.base.BaseController;
import cc.customer.web.util.BigEmpReadExcel;

@Controller
@RequestMapping("/bigEpResoure")
public class BigEpResoureController extends BaseController {

   private Logger logger = LoggerFactory.getLogger(BigEpResoureController.class);

   @Autowired
   private BigEmpServices bigEmpServicesOmp;
   @Autowired
   private BigEmpIrecords bigEmpIrecords;
   @Autowired
   private UserService userService;
   @Autowired
   private ExEmpServices exEmpServices;
   @Autowired
   private UserMapper userMapper;


   /**加载大名单主页**/
   @RequestMapping(value="/bigIndex")
   public String loadBigEpResoureIndex (){
      return "customer/BigEpResource/bigEpResoure/bigEpResoure_index";
   }
   /**新增客户**/
   @RequestMapping(value = "/addCustomerDialog")
   public String addCustomerDialog(){return "customer/BigEpResource/bigEpResoure/customer_emp";}
   /**加载大名单客户资料**/
   @RequestMapping(value = "/loadCustomerDetail")
   public String loadCustomerDetail(){
      return "customer/myCustomer/myCustomerdetail/bigEmpDetail";
   }

   /**
    * 新增客户验证手机号
    */
   @RequestMapping(value = "/checkUserMobile")
   @ResponseBody
   public Boolean checkUserMobile(String bpMobile){
      Boolean ble = FebsUtil.isPhoneNo(bpMobile);
      if(!ble){
         return false;
      }
      BigEmp bigEmp = bigEmpServicesOmp.findBigEmpByMobile(bpMobile);
      return  bigEmp == null;
   }
   /**下载模板**/
   @RequestMapping(value = "/downModal")
   @ResponseBody
   public ResponseBo downBigExcel(){
      try {
         BigEmp excel = new BigEmp();
         excel.setBpName("张三");
         excel.setBpSex("男");
         excel.setBpMobile("15253130150");
         excel.setBpQq("1114701778");
         excel.setBpGroud("A");
         excel.setBpCity("山东省");
         excel.setBpZone("章丘片区");
         excel.setBpColleges("山东大学");
         excel.setBpAcademy("信息学院");
         excel.setBpMajor("电子信息工程");
         excel.setBpYear("2018");
         excel.setBpSourChanel("宣讲会");
         excel.setBpInteProject("教师资格证");
         excel.setBpInteAipro("教师资格证");
         excel.setBpEducation("例：专科、本科、硕士、博士");
         List<BigEmp> list = new ArrayList<>();
         list.add(excel);
         return FileUtils.createExcelByPOIKit("大名单表格模板", list, BigEmp.class);
      } catch (Exception e) {
         return ResponseBo.error("导出Excel失败，请联系网站管理员！");
      }
   }

   @RequestMapping(value="/uploadFile",method= RequestMethod.POST,produces={"application/json;charset=UTF-8"})
   @ResponseBody
   public ResponseBo uploadBigEmpResource(MultipartFile[] file){
      if (file.length<=0){
         return ResponseBo.error("上传文件为空");
      }
      String  FilePath = Constant.BIGEMP_FILE_PATH;
      return FileUploadUtil.excuteFiles(FilePath,file);
   }


   /**校对大名单资源导入的表头**/
   @RequestMapping(value = "/bigEmpValiable",method = RequestMethod.POST)
   @ResponseBody
   public ResponseBo valiableBigEmpResource(String impUrl){
      //读取列术，查看内容，，自动义验证规则
      ResponseBo lis = BigEmpReadExcel.checkExcel(impUrl);
      //校对表头，，自定义校验规则
      return lis;
   }
   /**校对大资源资源意向资源的导入的表头**/
   @RequestMapping(value = "/bigEmpValiableExport",method = RequestMethod.POST)
   @ResponseBody
   public ResponseBo valiableBigEmpExport(String expUrl){
      //读取列术，查看内容，，自动义验证规则
      return BigEmpReadExcel.checkExcelExport(expUrl);
   }

   /**修改用户得基本信息**/
   @RequestMapping(value = "/bigempEditinfo")
   @ResponseBody
   public ResponseBo bigempEditinfo(BigEmp emp){
      MyUser user = this.getCurrentUser();
      emp.setBpRecent(user.getNickname()+Constant.GENZONG_RECORD_ZILAO);
      emp.setBpRecentTime(DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
      return bigEmpServicesOmp.updateBigEmpInfoByBpId(emp,user);
   }
   /**批量删除用户**/
   @RequestMapping(value = "/bigempDeleteinfo")
   @ResponseBody
   public ResponseBo bigempDeleteinfo(String ids){
      return bigEmpServicesOmp.batchUpdateBigEmp(ids);
   }

   /**批量更新客户的信息**/
   @RequestMapping(value = "/bigEmpbatchUpdateByEmp")
   @ResponseBody
   public  ResponseBo bigEmpbatchUpdateByEmp(BigEmp bigEmp,String ids){
      MyUser user = this.getCurrentUser();
      String userId  = user.getUserUuid();
      String username = user.getUsername();
      bigEmp.setBpDisPerson(userId);
      MyUser userFen = userService.findUserByUuids(bigEmp.getBpDistribute());
      bigEmp.setBpRecent(user.getNickname()+Constant.GENZONG_RECORD_FENPEI+userFen.getNickname());
      bigEmp.setBpRecentTime(DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
      return bigEmpServicesOmp.batchUpdateBykeyId(bigEmp,ids,username);
   }

   /**大名单初始信息信息导入**/
   @RequestMapping(value = "/bigEmpImport",method = RequestMethod.POST)
   @ResponseBody
   public ResponseBo ImportBigEmpResource(String impUrl,String batch,String director,String bpResType,String isBalan,HttpServletResponse response){
      System.out.println(DateUtil.getDateFormat(new Date(),"yyyy-MM-dd HH:mm:ss"));
      String uuid  = Utils.getUUID();
      Map<String,Object> map = BigEmpReadExcel.createExcel(impUrl,batch,bpResType,uuid,director);
      List<BigEmp> lis = new ArrayList<>();
      List<EprRecords> errorList = new ArrayList<>();
      //获取正确的导入集合信息
      if(null!=map&&map.containsKey("list")){
         lis = (List<BigEmp>)map.get("list");
      }
      
      //获取错误的导入集合信息
      ResponseBo res = new ResponseBo();
      if(null!=map&&map.containsKey("errorList")){
    	  errorList = (List<EprRecords>)map.get("errorList");
      }

      logger.info("获得得路径："+impUrl+"大小："+lis.size());
      try {
        MyUser user = this.getCurrentUser();
        String username = user.getUsername();
        EpRecords records = new EpRecords();
        records.setEpBatch(batch);
        records.setEpDirector(director);
        records.setEpNum(lis.size()+"");
        records.setEpOption(username);
        records.setEpTime(new Date());
        records.setEpType(bpResType);
        records.setEpUuid(Utils.getUUID());
        records.setEpBatchUuid(uuid);
        records.setEpBalanceIsbalan(isBalan);
        records.setEpBalanceNum("0");
        records.setEpBalanceOver("0");
        List<BigEmp> bigEmps = new ArrayList<>();
        List<EprRecords> allChongfu = new ArrayList<>();

        /**验证大资源数据重复的数据**/
        List<String> listAll = bigEmpServicesOmp.findAllBigEmp();
        /**验证推广资源是不是有重复得手机号**/
        List<String> listExemp =exEmpServices.getAllExEmpPhone();
        EprRecords epr  = null;
        for (BigEmp bigEmp1:lis){
           String edu = "";
           String eddd = bigEmp1.getBpEducation();
           if("2".equals(eddd)){edu = "专科";}else if("3".equals(eddd)){edu = "本科";}
           else if("4".equals(eddd)){edu = "硕士";}else if("5".equals(eddd)){edu = "博士";}
           String phone1 = bigEmp1.getBpMobile();
           if (listAll.contains(phone1)){
              epr = new EprRecords();
              epr.setcEprPhone(bigEmp1.getBpMobile());
              epr.setcEprUser(bigEmp1.getBpName());
              epr.setcEprTime(new Date());
              epr.setcEprBatch(bigEmp1.getBpBatch());
              epr.setcEprBacthUuid(records.getEpUuid());
              epr.setcEprReson("根据手机号查询,当前大资源已经存在资源");
              epr.setcEprSex(bigEmp1.getBpSex());
              epr.setcEprChu(bigEmp1.getBpInteProject());
              epr.setcEprQudao(bigEmp1.getBpSourChanel());
              epr.setcEprYi(bigEmp1.getBpInteAipro());
              epr.setcEprDeng(bigEmp1.getBpGroud());
              epr.setcEprQQ(bigEmp1.getBpQq());
              epr.setcEprCity(bigEmp1.getBpCity());
              epr.setcEprZone(bigEmp1.getBpZone());
              epr.setcEprCollage(bigEmp1.getBpColleges());
              epr.setcEprPace(bigEmp1.getBpAcademy());
              epr.setcEprZhuan(bigEmp1.getBpMajor());
              epr.setcEprYear(bigEmp1.getBpYear());

              epr.setcEprEdu(edu);
              allChongfu.add(epr);
           }else if (listExemp.contains(phone1)){
              epr = new EprRecords();
              epr.setcEprPhone(bigEmp1.getBpMobile());
              epr.setcEprUser(bigEmp1.getBpName());
              epr.setcEprTime(new Date());
              epr.setcEprBatch(bigEmp1.getBpBatch());
              epr.setcEprBacthUuid(records.getEpUuid());
              epr.setcEprReson("根据手机号查询,当前推广资源已经存在资源");
              epr.setcEprSex(bigEmp1.getBpSex());
              epr.setcEprChu(bigEmp1.getBpInteProject());
              epr.setcEprQudao(bigEmp1.getBpSourChanel());
              epr.setcEprYi(bigEmp1.getBpInteAipro());
              epr.setcEprDeng(bigEmp1.getBpGroud());
              epr.setcEprQQ(bigEmp1.getBpQq());
              epr.setcEprCity(bigEmp1.getBpCity());
              epr.setcEprZone(bigEmp1.getBpZone());
              epr.setcEprCollage(bigEmp1.getBpColleges());
              epr.setcEprPace(bigEmp1.getBpAcademy());
              epr.setcEprZhuan(bigEmp1.getBpMajor());
              epr.setcEprYear(bigEmp1.getBpYear());
              epr.setcEprEdu(edu);
              allChongfu.add(epr);
           }else{
              bigEmps.add(bigEmp1);
           }
        }
        if(errorList.size()>0){
           for(EprRecords records1:errorList){
              records1.setcEprBacthUuid(records.getEpUuid());
           }
        }
         allChongfu.addAll(errorList);
        /**批量插入数据**/
        List<List<BigEmp>> liust = Utils.averageAssign(bigEmps,1500);
        /**启用三个线程 同步处理**/
        List<BigEmp> listOne = new ArrayList<>();
        List<BigEmp> listtwo = new ArrayList<>();
        List<BigEmp> listThree = new ArrayList<>();
        int i = 1;
        int size = liust.size();
        if ( size >=3){
           for (List<BigEmp> list :liust){
              if (i == 1){
                 listOne.addAll(list);i = 2;
              } else if (i == 2){
                 listtwo.addAll(list);i = 3;
              }else{
                 listThree.addAll(list);i = 1;
              }
           }
        }else{
            if (size == 1){
               listOne.addAll(liust.get(0));
            }else if (size == 2){
               listOne.addAll(liust.get(0));
               listtwo.addAll(liust.get(1));
            }
        }
         Future<Integer> listall =  bigEmpServicesOmp.batchInsertOne(listOne,records);
         Future<Integer> listall1 = bigEmpServicesOmp.batchInsertThree(listThree,records);
         Future<Integer> listall2 =   bigEmpServicesOmp.batchInsertTwo(listtwo,records);
         int num = listall.get()+listall1.get()+listall2.get();
         records.setEpFNum(allChongfu.size()+"");
         records.setEpDtype(Constant.ZIYUAN_TYPE_SCHOLLE);
         try {
            bigEmpServicesOmp.insertRecord(allChongfu,records);
         }catch (Exception e){
            e.printStackTrace();
            return ResponseBo.error("数据导入成功,生成导入记录失败");
         }

        if(num>0&&allChongfu.size()<1){
           return ResponseBo.ok("noError","导入成功，没有错误和重复数据");
        }else if(num>0&&allChongfu.size()>0){
           return ResponseBo.ok("hasError",records.getEpUuid());
        }else if(num==0&&allChongfu.size()>0){
           return ResponseBo.ok("isError",records.getEpUuid());
        }else if(num==0&&allChongfu.size()==0){
           return ResponseBo.ok("isNull",records.getEpUuid());
        }
     }catch (Exception e){
        e.printStackTrace();
     }
      return ResponseBo.error("导入失败");
   }
   /**大名单意向等级信息更新**/
   @RequestMapping(value = "/bigEmpGroupImport",method = RequestMethod.POST)
   @ResponseBody
   public ResponseBo createExcelExport(String expUrl){
      List<BigEmp> lis = BigEmpReadExcel.createExcelExport(expUrl);
      logger.info("获得得路径："+expUrl+"大小："+lis.size());
      int num = 0;
      try {
         MyUser user = this.getCurrentUser();
          num = bigEmpServicesOmp.batchUpdateInten(lis,user.getUsername());
         System.out.println("批量更新得条数: "+num);
      }catch (Exception e){
         e.printStackTrace();
         return ResponseBo.error("更新失败");
      }
      return ResponseBo.ok(num);
   }

   /**获取大名单资源信息**/
   @RequestMapping("/list")
   @ResponseBody
   public Map<String, Object> dictList(QueryRequest request, BigEmp bigEmp,String isBig) {
      MyUser user = this.getCurrentUser();
      List<String> list = new ArrayList<>();
      /**筛选部门*/
      if(!StringUtils.isEmpty(bigEmp.getBpDeptId())){
         List<MyUser> userList = userMapper.findUserByDepid(bigEmp.getBpDeptId());
         if(userList.size()>0){
            for(MyUser user1:userList){
               list.add(user1.getUserUuid());
            }
         }
      }
      return super.selectByPageNumSize(request, () -> this.bigEmpServicesOmp.findAllBigEmp(bigEmp,request,isBig,user,list));
   }

   /**获取大名单资源信息**/
   @RequestMapping("/listMyCustomer")
   @ResponseBody
   public Map<String, Object> listMyCustomer(QueryRequest request, BigEmp bigEmp) {
      MyUser user = this.getCurrentUser();
      return super.selectByPageNumSize(request, () -> this.bigEmpServicesOmp.findMyAllBigEmp(bigEmp,user));
   }

   /**手动新增客户名单**/
   @RequestMapping("/addBigEmp")
   @PreAuthorize("hasAuthority('bigemp:add')")
   @ResponseBody
   public ResponseBo addBigEmp(BigEmp emp){
      try {
         return bigEmpServicesOmp.addBigEmp(emp);
      }catch (Exception e){
      }
      return ResponseBo.error("增加失败");
   }

   /**手动新增客户名单-新增我的客户**/
   @RequestMapping("/addBigEmpByMe")
   @ResponseBody
   public ResponseBo addBigEmpByMe(BigEmp emp){
      try {
         String userid = this.getCurrentUser().getUserUuid();
         emp.setBpDistribute(userid);
         emp.setBpIsdelete("0");
         emp.setBpStage("1");
         emp.setBpResType("1");
         return bigEmpServicesOmp.addBigEmp(emp);
      }catch (Exception e){
      }
      return ResponseBo.error("增加失败");
   }

   /**查询客户的详情**/
   @RequestMapping("/viewBigEmpDetail")
   @ResponseBody
   public ResponseBo viewBigEmpDetail(String keyid){
      MyUser user = this.getCurrentUser();
      return bigEmpServicesOmp.findAllBigEmpInfoById(keyid,user);
   }

   @RequestMapping("/getBigEmpDetailLabel")
   @ResponseBody
   public ResponseBo getBigEmpDetailLabel(String keyid){
      return bigEmpServicesOmp.selectBigEmpLabel(keyid);
   }


   /**大资源客户导出客户信息的 记录**/
   @RequestMapping("/exportBigEmpDetail")
   @ResponseBody
   public ResponseBo exportBigEmpDetail(BigEmp bigEmp,String ids,String exportMsg){
      try {
         String name = this.getCurrentUser().getUsername();
         bigEmpServicesOmp.exportBigEmpRecords(bigEmp,ids,name,exportMsg);
         return ResponseBo.ok("导出记录成功");
      }catch (Exception e){
         logger.error("大资源名单导出大资源客户失败："+e.getMessage());
      }
      return ResponseBo.error("导出失败");
   }
   /**大资源客户导出excel**/
   @RequestMapping("/exportBigEmpDetailforExcel")
   @ResponseBody
   public ResponseBo exportBigEmpDetailforExcel(String keyids){
      try {
         MyUser user = this.getCurrentUser();
         List<BigEmp> list = bigEmpServicesOmp.exportBigEmpInfo(keyids,user);
         ResponseBo responseBo = FileUtils.createExcelByPOIKit("客户资料表", list, BigEmp.class);
         return responseBo;
      }catch (Exception e){
         logger.error("大资源名单导出大资源客户失败："+e.getMessage());
      }
      return ResponseBo.error("导出失败");
   }

   /**
    * 根据uuid 查询当前批次导入的 客户信息
    * **/
   @RequestMapping("/getexportBigEmpbyUuid")
   @ResponseBody
   public Map<String, Object> getexportBigEmpbyUuid(QueryRequest request,String idsUuid,String condition){
      return super.selectByPageNumSize(request, () -> this.bigEmpServicesOmp.findBigEmpByImportUuid(idsUuid,condition));
   }

   /**根据当前导出的批次 查询当前导出的批次下的人员**/
   @RequestMapping(value = "/exportbatchUser")
   @ResponseBody
   public Map<String,Object> exportbatchUser(QueryRequest queryRequest,Long ipRecordIds){
      MyUser user = this.getCurrentUser();
      IpRecords records = this.bigEmpIrecords.getexportBatchCustomer(ipRecordIds);
      Map<String,Object> map =super.selectByPageNumSize(queryRequest,
              () -> this.bigEmpServicesOmp.exportBigEmpInfo(records.getcIpIds(),user));
      JSONObject json = JSONObject.parseObject(records.getcIpIcomdtion());
      map.put("condition",json);
      return map;
   }

   /**根据当前导入的批次 查询当前导出的批次下的人员**/
   @RequestMapping(value = "/importbatchUser")
   @ResponseBody
   public Map<String,Object> importbatchUser(Long ipRecordIds,QueryRequest queryRequest){
      IpRecords records = this.bigEmpIrecords.getexportBatchCustomer(ipRecordIds);
      return super.selectByPageNumSize(queryRequest,() -> this.bigEmpServicesOmp.findBigEmpByImportBatch(records.getcIpEname()));
   }
}